#!/bin/bash

FRONTEND='java -cp frontend/bin DVDSystem '
BACKEND='java -cp backend/bin Backend '
TRANSDIR='transactions'
DVDFILE='empty.dvd'
MDVDFILE='empty.mdvd'

# declare an array for the names of the test dirs
# declare -a TDIRS

if [ -z $1 ]
then
    echo "Usage: daily.sh <day#> [.dvd file] [.mdvd file]"
    exit 1
fi

TD=$TRANSDIR/$1

# set .dvd file if provided or default to empty
if [ -z $2 ]
then
    DVDFILE=$TRANSDIR/$DVDFILE
else
    DVDFILE=$TRANSDIR/$2
fi

# set .mdvd file if provided or default to empty
if [ -z $3 ]
then
    MDVDFILE=$TRANSDIR/$MDVDFILE
else
    MDVDFILE=$TRANSDIR/$3
fi

for i in $( ls $TD | grep .txt | sed 's/\(.*\)\..*/\1/' ); do
    cat $TD/$i.txt | $FRONTEND $DVDFILE $TD/$i.tf > /dev/null
done

TF=$( ls -1 $TD | grep [.]tf )

if [[ -n $TF ]]
then
    cat $TD/*.tf > $TD/merged.mtf
    echo "00                           000   000.00" >> $TD/merged.mtf
else
    echo -e '\E[48;31m'"\033[1mFrontend failed to create transaction files\033[0m"
    exit 1
fi

$BACKEND $TD/merged.mtf $MDVDFILE $TRANSDIR/master.mdvd $TRANSDIR/current.dvd